package com.tsystems.train.bean;

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import com.tsystems.train.entity.Station;
import com.tsystems.train.service.StationServices;
import com.tsystems.train.validator.MyValidator;

@Named("stationTableBean")
@RequestScoped
public class StationTableBean implements Serializable {

	private static final long serialVersionUID = 2165793273424547096L;


	
	@EJB
	private StationServices stationService;
	
	@Inject
	private BuyTicketBean buyTicketBean;

	private String name;
	private StationTableDataModel stationTableDataModel;
	private Station selectedStation= new Station();

	public StationTableBean() {
		stationTableDataModel=new StationTableDataModel();
		selectedStation= new Station();
	}
	
	@PostConstruct
    public void init() {
    	    	updateTable();
    }
	
	
	public void updateTable() {
		List<Station> result = stationService.viewStations();
		stationTableDataModel.setWrappedData(result);
		
	}
	public String addStation() {
		name.trim();
		Station station = new Station(name);
		if (!MyValidator.validate(station)){
			return null;
		}
		String result = stationService.addStation(station);
		if (result.equals("New station added")) {
			updateTable();
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_INFO,
							"Add info", result));
		}else{
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Add error", result));
		}
		StationConverter.stations = stationService.viewStations();
		buyTicketBean.setStations(StationConverter.stations);
		
		return null;
	}

	public Station getSelectedStation() {
		return selectedStation;
	}

	public void setSelectedStation(
			Station selectedStation) {
		this.selectedStation = selectedStation;
	}

	

	public StationTableDataModel getStationTableDataModel() {
		return stationTableDataModel;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	
	                       
}
